package top.jacktgq.itheima.netty.future.compare;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

/**
 * @Author CandyWall
 * @Date 2021/3/22--23:33
 * @Description
 */
@Slf4j
public class TestNettyFuture {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        // 1.线程池
        EventLoop eventLoop = group.next();
        // 2.提交任务
        Future<Integer> future = eventLoop.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                log.debug("执行计算...");
                Thread.sleep(5000);
                return 50;
            }
        });

        // 3.主线程通过future获得结果
        // 3.1 同步方式
        /*log.debug("等待结果...");
        Integer result = future.get();
        log.debug("结果是：{}", result);*/
        // 3.2 异步方式
        future.addListener(new GenericFutureListener<Future<? super Integer>>() {
            @Override
            public void operationComplete(Future<? super Integer> future) throws Exception {
                log.debug("结果是：{}", future.getNow());
            }
        });
    }
}
